local Utils = require"ecs.utils.utils"

local sandbox_area_utils = class("SandboxAreaUtils",Utils){}
local bit = require"bit"

local TILESET_BIT_SIZE = 16
local TILE_BIT_SIZE = 32 - TILESET_BIT_SIZE
local TILESET_BIT = 0x0000ffff;

function sandbox_area_utils.to_tileindex(tileset,tile)
    return bit.bor(bit.lshift(tileset,TILESET_BIT_SIZE),tile)
end

function sandbox_area_utils.get_tileset(tileindex)
    return bit.rshift(tileindex,TILESET_BIT_SIZE)
end

function sandbox_area_utils.get_tile(tileindex)
    return bit.band(tileindex,TILESET_BIT)
end

function sandbox_area_utils.set_tile(x,y,tileindex)
    local sandbox = box_core.get_shared("Sandbox")
    local area = sandbox:get_area_from_wposi(x,y)
    love.graphics.setCanvas(area.canvas)
        --love.graphics.setBlendMode("replace")
        local tileset = box_core.assets.tileset(sandbox_area_utils.get_tileset(tileindex))
        if tileset then
            x,y = sandbox.wpos_to_gposi(x,y)
            local glx,gly = x - (area.x * SANDBOX_AREA_SIZE),y - (area.y * SANDBOX_AREA_SIZE)
            tileset:draw(
                sandbox_area_utils.get_tile(tileindex),
                glx * SANDBOX_GRID_PSIZE,
                gly * SANDBOX_GRID_PSIZE
            )
        end
    love.graphics.setCanvas()
end

return sandbox_area_utils()